package com.slicktechnologies.client.views.home;

import java.util.ArrayList;
import java.util.Vector;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.view.client.NoSelectionModel;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.simplesoftwares.client.library.appskeleton.AppMemory;
import com.simplesoftwares.client.library.appstructure.SuperModel;
import com.simplesoftwares.client.library.appstructure.SuperTable;
import com.simplesoftwares.client.library.appstructure.search.Filter;
import com.simplesoftwares.client.library.appstructure.search.MyQuerry;
import com.simplesoftwares.client.library.libservice.GenricService;
import com.simplesoftwares.client.library.libservice.GenricServiceAsync;
import com.slicktechnologies.client.utility.Screen;
import com.slicktechnologies.client.views.contract.ContractForm;
import com.slicktechnologies.client.views.contract.ContractPresenter;
import com.slicktechnologies.shared.Contract;
import com.slicktechnologies.shared.Sales;

public class HomePresenter implements ClickHandler
{
	
	HomeForm form;
	HomePresenterSearchProxy searchpopup;
	protected GenricServiceAsync service=GWT.create(GenricService.class);
	
	public  HomePresenter(HomeForm form,HomePresenterSearchProxy searchpopup)
	{
		this.form=form;
		this.searchpopup=searchpopup;
		SetEventHandling();
		searchpopup.applyHandler(this);
		
		Filter filter = new Filter();
		
		//Create Querry For Lead
		MyQuerry querry=new MyQuerry();
	
		
		
		///////////Create Querry For Contract/////////////////////////////////////////////////////
		filter = new Filter();
		filter.setQuerryString("status");
		filter.setStringValue(Contract.CREATED);
		querry=new MyQuerry();
		querry.setQuerryObject(new Contract());
		querry.getFilters().add(filter);
		retriveTable(querry,form.getContractTable());
		setTableSelectionOnContract();
		
		}
	
	public static void initalize()
	{
		HomeForm homeForm = new HomeForm();
		AppMemory.getAppMemory().currentScreen=Screen.HOME;
		AppMemory.getAppMemory().skeleton.getProcessName().setText("Dashboard/Home");
		HomePresenterSearchProxy searchpopup=new HomePresenterSearchProxy();
		HomePresenter presenter= new HomePresenter(homeForm,searchpopup);
		AppMemory.getAppMemory().stickPnel(homeForm);	
	}
	
	
	
	
	@Override
	public void onClick(ClickEvent event) {
		
		if(event.getSource() instanceof InlineLabel)
		{
		InlineLabel lbl= (InlineLabel) event.getSource();
		String text= lbl.getText();
		if(text.equals("Search"))
			searchpopup.showPopUp();
		
		if(text.equals("Go"))
			reactOnGo();
		}
			
	}
	
	/**
	 * Sets the event handling.
	 */
	public void SetEventHandling()
	{
		 InlineLabel label[] =AppMemory.getAppMemory().skeleton.getMenuLabels();
		  for(int k=0;k<label.length;k++)
		  {
			 if( AppMemory.getAppMemory().skeleton.registration[k]!=null)
			    AppMemory.getAppMemory().skeleton.registration[k].removeHandler();
			 
				 
		  }
		 
		  for( int k=0;k<label.length;k++)
		  {
			  
			  AppMemory.getAppMemory().skeleton.registration[k]= label[k].addClickHandler(this);
		  }
	}

	public void reactOnGo()
	{ 

		MyQuerry quer=createSalesFilter(new Contract());
		 this.form.contractTable.connectToLocal();
		retriveTable(quer, form.getContractTable());
		searchpopup.hidePopUp();
	
	}
	
	
	
	private MyQuerry createSalesFilter(Sales sales)
	{
		Vector<Filter>filterVec = new Vector<Filter>();
		 Filter temp;
		 if(searchpopup.personInfo.getId().getText().trim().equals("")==false)
			{
				temp=new Filter();
				temp.setLongValue(Long.parseLong(searchpopup.personInfo.getId().getValue()));
				temp.setQuerryString("cinfo.count");
				filterVec.add(temp);	
			}
			
			if((searchpopup.personInfo.getName().getText()).trim().equals("")==false)
			{
				temp=new Filter();
				temp.setStringValue(searchpopup.personInfo.getName().getValue());
				temp.setQuerryString("cinfo.fullName");
				filterVec.add(temp);	
			}
			
			if(searchpopup.personInfo.getPhone().getText().trim().equals("")==false)
			{
				temp=new Filter();
				temp.setLongValue(Long.parseLong(searchpopup.personInfo.getPhone().getValue()));
				temp.setQuerryString("cinfo.cellNumber");
				filterVec.add(temp);	
			}
			
			MyQuerry quotation=new MyQuerry();
			quotation.setFilters(filterVec);
			quotation.setQuerryObject(sales);
			
			return quotation;
	}
	
	
	
	
	
	public void setContractRedirection()
	 {
		    
	 }

	 public void setLeadRedirection()
	 {
		 
	 }
	 
	 public void setServiceRedirection()
	 {
		 	
			
	 }
	 
	 public void setQuotationRedirection()
	 {
		    
			
	 }	
	
	
	
	
	 
	 
	 public void setTableSelectionOnContract()
	 {
		 final NoSelectionModel<Contract> selectionModelMyObj = new NoSelectionModel<Contract>();
	     
	     SelectionChangeEvent.Handler  tableHandler = new SelectionChangeEvent.Handler() 
	     {
	         @Override
	         public void onSelectionChange(SelectionChangeEvent event) 
	         {
	        	 setContractRedirection();
	        	 AppMemory.getAppMemory().setCurrentScreenandChangeProcessName("Sales/Contract",Screen.CONTRACT);
	        	 final Contract entity=selectionModelMyObj.getLastSelectedObject();
	        	 final ContractForm form = ContractPresenter.initalize();
	        	
				
					
					form.showWaitSymbol();
					 AppMemory.getAppMemory().stickPnel(form);
	        	 Timer timer=new Timer() {
	 				
	 				@Override
	 				public void run() {
	 					 form.hideWaitSymbol();
	 					 form.getPersonInfoComposite().setEnable(false);
					     form.updateView(entity);
					     form.setToViewState();
					    
	 			             
	 				}
	 			};
	            
	             timer.schedule(5000); 
	                         
	          }
	     };
	     // Add the handler to the selection model
	     selectionModelMyObj.addSelectionChangeHandler( tableHandler );
	     // Add the selection model to the table
	     form.contractTable.getTable().setSelectionModel(selectionModelMyObj);
	     
		 
		 
	 }
	 
	 
	
	 
	 
	 public <T> void retriveTable(MyQuerry querry,final SuperTable<T>table)
	 {
		 
				table.connectToLocal();
				service.getSearchResult(querry,new AsyncCallback<ArrayList<SuperModel>>() {
					
					@Override
					public void onSuccess(ArrayList<SuperModel> result) {
						
						for(SuperModel model:result)
						{
							table.getListDataProvider().getList().add((T) model);
						}
					}
					
					@Override
					public void onFailure(Throwable caught) {
					caught.printStackTrace();
						
					}
				}); 
	 }

	
	
	
}
